package com.googlecode.cswish.struts;

import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

import com.googlecode.cswish.security.SafeManager;
import com.googlecode.cswish.security.UserTracerService;
import com.googlecode.cswish.security.auth.UserInfo;
import com.googlecode.cswish.struts.spring.ObjectFactory;

public class SessionListener implements HttpSessionListener {

	private UserTracerService userTracerService;
	
	public void sessionCreated(HttpSessionEvent event) {
		HttpSession session = event.getSession();
		getUserTracerService().sessionCreated(session);
	}

	public void sessionDestroyed(HttpSessionEvent event) {
		HttpSession session = event.getSession();
		UserInfo user = SafeManager.getInstance().getLoginUser(session);
		if (user != null && user != SafeManager.ANOY_USER) {		// user logout or user never logins
			getUserTracerService().logout(user.getLoginId());
		}
		
		getUserTracerService().sessionDestroyed(session);
	}

	private UserTracerService getUserTracerService() {
		if (userTracerService == null) {
			userTracerService = ObjectFactory.getInstance().getBean(UserTracerService.class, false);
		}
		return userTracerService;
	}
}